package com.hzdl.apple.dao.imp;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import com.hzdl.apple.bean.cart.CartItem;
import com.hzdl.apple.bean.cart.Order;
import com.hzdl.apple.bean.cart.OrderItem;

import com.hzdl.apple.dao.BaseDaoImp;
import com.hzdl.apple.dao.OrderDao;

public class OrderDaoImp extends BaseDaoImp implements OrderDao {

	@Override
	public boolean addOrder(Order order, Connection conn) {
		sql = "insert into orderA values(?,?,?,?,?,?,?)";
		try {
			qr.update(conn, sql, null, order.getUID(), order.getOrderTime(), order.getType(), order.getUAddress(),
					order.getUPhoneNum(), order.getShr());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public int getId(Connection conn) {
		sql = "select @@IDENTITY";
		try {
			Map<String, Object> map = qr.query(conn, sql, new MapHandler());
			BigInteger id = (BigInteger) map.get("@@IDENTITY");
			return id.intValue();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public boolean addOrderItem(OrderItem item, Connection conn, int UID) {
		sql = "insert into orderitem values(?,?,?,?,?,?,?,?)";
		try {
			int c = qr.update(conn, sql, null, item.getOID(), UID, item.getGoodsID(), item.getGoodsName(),
					item.getGoodsPrice(), item.getAllPrice(), item.getNums());
			if (c != 0) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public List<OrderItem> getOrderItem(int UID, int OID) {
		if (OID == 0) {
			sql = "select * from orderitem where UID=?";

			try {
				return qr.query(sql, new BeanListHandler<>(OrderItem.class), UID);
			} catch (SQLException e) {
				e.printStackTrace();
			}

			return null;
		} else {
			sql = "select * from orderitem where UID=? and OID=?";

			try {
				return qr.query(sql, new BeanListHandler<>(OrderItem.class), UID, OID);
			} catch (SQLException e) {
				e.printStackTrace();
			}

			return null;
		}
	}

	@Override
	public List<Order> getOrder(int UID) {
		sql = "select * from orderA where UID=?";
		try {
			return qr.query(sql, new BeanListHandler<>(Order.class), UID);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public boolean changeTypeByUOID(int OID,int type) {
		sql="update orderA set Type = ? where OID = ?";
		try {
			qr.update(sql,type,OID);
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

}
